<?php

namespace App\Services;

use App\Exceptions\ApiException;

use App\Http\Requests\Api\SendEmailRequest;
use App\Mail\Authorized;
use Illuminate\Support\Facades\Mail;

class EmailService
{
    public function store(SendEmailRequest $request)
    {
        $email = $request->email;

        if (app()->environment('production')) {

            $code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);

            $mail = Mail::to($email);

            $mail->send(new Authorized($code));
        } else {
            $code = 1234;
        }

        $expiredAt = now()->addMinutes(10);

        // 缓存验证码 10分钟过期。
        \Cache::put($email, ['email' => $email, 'code' => $code], $expiredAt);

        return [
            'verification_code' => $code,
            'expired_at' => $expiredAt->toDateTimeString(),
        ];
    }

    public function verify($email, $verification_code)
    {
        $verifyData = \Cache::get($email);

        if (!$verifyData) {
            throw new ApiException(trans('api.verification_code_expired'), 422);
        }

        if (!hash_equals((string)$verifyData['code'], (string)$verification_code)) {
            throw new ApiException(trans('api.verification_code_invalid'), 401);
        }

        // 清除验证码缓存
        \Cache::forget($email);

        return true;
    }
}
